import logging
import grpc
from concurrent import futures
from typing import Any, Dict
from ..proto import risk_service_pb2, risk_service_pb2_grpc
from ..core.risk_agent import RiskAgent

logger = logging.getLogger(__name__)

class RiskServiceImpl(risk_service_pb2_grpc.RiskServiceServicer):
    """风控服务实现（gRPC服务端）"""
    
    def __init__(self, risk_agent: RiskAgent):
        self.agent = risk_agent
        
    def PreCheckOrder(self, request, context) -> risk_service_pb2.RiskCheckResponse:
        """订单预检接口"""
        try:
            result = self.agent.pre_check_order({
                'id': request.order_id,
                'symbol': request.symbol,
                'quantity': request.quantity,
                'price': request.price
            })
            
            return risk_service_pb2.RiskCheckResponse(
                passed=result['passed'],
                details=str(result['details'])
            )
        except Exception as e:
            context.set_code(grpc.StatusCode.INTERNAL)
            context.set_details(f'风控检查失败: {str(e)}')
            return risk_service_pb2.RiskCheckResponse()
            
    def GetRiskStatus(self, request, context) -> risk_service_pb2.RiskStatus:
        """获取风控状态"""
        return risk_service_pb2.RiskStatus(
            circuit_breaker=False,
            risk_level=0,
            active_alerts=[]
        )

def serve():
    """启动gRPC服务"""
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    risk_service_pb2_grpc.add_RiskServiceServicer_to_server(
        RiskServiceImpl(RiskAgent(config={})), server)
    server.add_insecure_port('[::]:50052')
    server.start()
    logger.info("风控服务已启动，监听端口 50052")
    server.wait_for_termination()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    serve()